<template>
  <el-form
    ref="formRef"
    :model="model"
    :rules="rules"
    :label-width="labelWidth"
    :label-position="labelPosition"
    :size="size"
    :disabled="disabled"
    v-bind="$attrs"
  >
    <slot />
  </el-form>
</template>

<script setup lang="ts">
import { ref, provide } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'

interface Props {
  model: Record<string, any>
  rules?: FormRules
  labelWidth?: string | number
  labelPosition?: 'left' | 'right' | 'top'
  size?: 'large' | 'default' | 'small'
  disabled?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  labelWidth: '120px',
  labelPosition: 'right',
  size: 'default',
  disabled: false
})

const emit = defineEmits<{
  validate: [valid: boolean]
  resetFields: []
  clearValidate: []
}>()

const formRef = ref<FormInstance>()

// 提供表单实例给子组件
provide('formRef', formRef)

// 验证表单
const validate = async (): Promise<boolean> => {
  if (!formRef.value) return false
  
  try {
    await formRef.value.validate()
    emit('validate', true)
    return true
  } catch {
    emit('validate', false)
    return false
  }
}

// 验证指定字段
const validateField = (props: string | string[]) => {
  formRef.value?.validateField(props)
}

// 重置表单
const resetFields = () => {
  formRef.value?.resetFields()
  emit('resetFields')
}

// 清除验证
const clearValidate = (props?: string | string[]) => {
  formRef.value?.clearValidate(props)
  emit('clearValidate')
}

// 暴露方法
defineExpose({
  validate,
  validateField,
  resetFields,
  clearValidate
})
</script>

<style scoped lang="scss">
.el-form {
  .el-form-item {
    margin-bottom: 18px;
  }
}
</style>
